﻿using System;
using System.IO.IsolatedStorage;
using nyxwin.Common.Base.Common;

namespace nyxwin.Common.Settings
{
    public sealed class ApplicationSettings : NotifyingObject
    {
        #region Instance

        private static ApplicationSettings _instance;
        private static object _lock = new object();

        public static ApplicationSettings Instance
        {
            get
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new ApplicationSettings();
                    }
                    return _instance;
                }
            }
        }

        #endregion

        #region Fields

        private readonly IsolatedStorageSettings _isolated;

        #endregion

        #region Construction

        private ApplicationSettings()
        {
            _isolated = IsolatedStorageSettings.ApplicationSettings;
        }

        #endregion

        #region Save

        internal void Save(string key, object value)
        {
            if (_isolated.Contains(key))
                _isolated[key] = value;
            else
                _isolated.Add(key, value);

            _isolated.Save();
        }

        #endregion

        #region Load

        internal T Load<T>(string key, T defaultValue)
        {
            if (_isolated.Contains(key))
                return (T) _isolated[key];

            return defaultValue;
        }

        internal T Load<T>(string key)
        {
            T value = default(T);
            return Load(key, value);
        }

        #endregion

        #region Properties

        public string AuthorizationNick
        {
            get { return Load("authorizationNick", string.Empty); }
            set { Save("authorizationNick", value); RaisePropertyChanged(() => AuthorizationNick); }
        }

        public string AuthorizationToken
        {
            get { return Load("authorizationToken", string.Empty); }
            set { Save("authorizationToken", value); RaisePropertyChanged(() => AuthorizationToken); }
        }

        public string AuthorizationCode
        {
            get { return Load("authorizationCode", string.Empty); }
            set { Save("authorizationCode", value); RaisePropertyChanged(() => AuthorizationCode); }
        }

        #endregion
    }
}